package tree.binarysearchtree;

import tree.TreeNode;

/**
 * @Classname : MinimumAbsoluteDifferenceInBst
 * @Description :
 * <a href="https://leetcode.cn/problems/minimum-absolute-difference-in-bst/">530. 二叉搜索树的最小绝对差</a>
 * @Author : chentianyu
 * @Date 2023/1/22 10:08
 */


public class MinimumAbsoluteDifferenceInBst {
    private int pre;
    private int minimumDifference;
    private final int MAX_VALUE = 100000;

    public int getMinimumDifference(TreeNode root) {
        // 每次调用方法需要对全局变量初始化
        pre = -1;
        minimumDifference = MAX_VALUE;
        // 树中任意两不同节点值之间的最小差值 ==> BST中序遍历（正序）计算相邻节点最小差值
        getMinimumDifferenceHelper(root);
        return minimumDifference;
    }

    private void getMinimumDifferenceHelper(TreeNode root) {
        if (root == null) return;

        getMinimumDifferenceHelper(root.left);
        if (pre != -1) minimumDifference = Math.min(minimumDifference, root.val - pre);
        pre = root.val;
        getMinimumDifferenceHelper(root.right);
    }
}
